package com.creditcmsplt.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.creditcmsplt.entity.CreditCsv;
import com.creditcmsplt.entity.CreditCsvConvert;
import com.creditcmsplt.entity.CreditCvthpdf;
import com.creditcmsplt.entity.param.CreditApplyCreditReportReq;
import com.creditcmsplt.entity.param.CreditApplyCreditReportRsp;
import com.creditcmsplt.entity.param.CreditApplyCreditReportRspData;
import com.creditcmsplt.entity.param.CreditConvertPdfReq;
import com.creditcmsplt.entity.param.CreditConvertPdfRsp;
import com.creditcmsplt.entity.param.CreditConvertPdfRspData;
import com.creditcmsplt.entity.param.CreditCrdDldReq;
import com.creditcmsplt.entity.param.CreditCrdDldRsp;
import com.creditcmsplt.entity.param.CreditCrdDldRspData;
import com.creditcmsplt.entity.param.CreditGetCreditReportReq;
import com.creditcmsplt.entity.param.CreditGetCreditReportRsp;
import com.creditcmsplt.entity.param.CreditGetCreditReportRspData;
import com.creditcmsplt.properties.CrdPdfConvertProperties;
import com.creditcmsplt.service.CreditApiService;
import com.creditcmsplt.service.CreditAuothService;
import com.creditcmsplt.service.CreditCsvConvertService;
import com.creditcmsplt.service.CreditCsvService;
import com.creditcmsplt.service.CreditCvthpdfService;
import com.creditcmsplt.service.CreditLogService;
import com.creditcmsplt.util.AesUtil;
import com.creditcmsplt.util.Base64Util;
import com.creditcmsplt.util.FileUtil;
import com.creditcmsplt.util.HttpUtil;
import com.creditcmsplt.util.OssUtil;
import com.creditcmsplt.util.PDFTextReader;
import com.creditcmsplt.util.PdfToImageUtil;
import com.creditcmsplt.util.RandomUtil;
import com.creditcmsplt.util.TextUtils;
import com.creditcmsplt.util.UUIDUtil;
import com.creditcmsplt.util.ZipUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 征信报告下载(PDF转csv接口)
 * 
 * @author 雷阳军
 *
 */

@RestController
@RequestMapping("credit")
@Api(value = "credit", tags = { "4.0,pdf报告转换" },description="credit")
public class CreditReportControlller {

	private final Logger log = LoggerFactory.getLogger(CreditReportControlller.class);

	@Autowired
	private CreditLogService creditLogService;

	@Autowired
	private CreditAuothService creditAuothService;

	@Autowired
	private CreditCsvConvertService creditCsvConvertService;

	@Autowired
	private CreditCsvService creditCsvService;

	@Autowired
	private CrdPdfConvertProperties crdPdfConvertProperties;
	
	@Autowired
	private CreditApiService creditApiService;
	
	@Autowired
	private CreditCvthpdfService creditCvthpdfService;

	/**
	 * 征信报告pdf转csv
	 * 
	 * @return
	 */
	@ApiOperation(value="发起pdf报告转换申请",notes="如有需求将pdf报告转换为excel或word可以用此接口,pdf只能是报告文件切为表格版pdf,非图片版")
	@RequestMapping(value = "/applyCreditReport", method = RequestMethod.POST)
	public CreditApplyCreditReportRsp applyCreditReport(@RequestBody CreditApplyCreditReportReq params,HttpServletRequest req) {
		CreditApplyCreditReportRsp result=new CreditApplyCreditReportRsp();
		CreditApplyCreditReportRspData data=new CreditApplyCreditReportRspData();
		Integer code=1;
		String msg="申请成功";
		String downloadcode="";
		if(params.getSystem()==null||
				params.getData()==null||
				TextUtils.isEmpty(params.getSystem().getVendor_key())||
				TextUtils.isEmpty(params.getSystem().getVendor_secret())||
				TextUtils.isEmpty(params.getData().getConvertType())) {
			code=-1;
			msg="缺少必须参数";
		}
		if(code.equals(1)&&TextUtils.isEmpty(params.getData().getIdentify())&&(params.getData().getPdfs()==null||params.getData().getPdfs().size()<=0)) {
			code=-1;
			msg="缺少转换征信报告必须参数,身份证号码或pdf自有文档";
		}
		if(code.equals(1)&&!(params.getData().getConvertType().equals("word")||params.getData().getConvertType().equals("excel"))) {
			code=-1;
			msg="转换类型不正确,目前支持word,excel两种";
		}
		if(code.equals(1)&&params.getData().getPdfs()!=null&&params.getData().getPdfs().size()>5) {
			code=-1;
			msg="自有pdf文件转换最多支持单次五次转换";
		}
		data=roleCheck(params.getSystem().getVendor_key(),params.getSystem().getVendor_secret(),params.getData().getIdentify());//校验是否厂商,或者是否身份证号码是他的所属
		if(code.equals(1)&&!data.getCode().equals(1)) {
			code=data.getCode();
			msg=data.getMsg();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//存储目录
		String date = sdf.format(new Date());
		sdf.applyPattern("HH");
		String monthDay = sdf.format(new Date());
		//上传oss 开始
		Map<String,Object> ossFileNameList=code.equals(1)?uploadOSS(params,date,monthDay):new HashMap<String,Object>();
		//上传oss 结束
		//通知 ocr转换 开始
		Integer status=code.equals(1)?actionOcr(params, ossFileNameList,date,monthDay):0;//0:失败,1:成功
		msg=code.equals(1)&&!status.equals(1)?"转换失败":msg;
		code=code.equals(1)&&!status.equals(1)?-1:code;
		//通知ocr转换结束
		//持久化数据 开始
		downloadcode=code.equals(1)&&!status.equals(0)?saveDate(params, ossFileNameList):"";
		//持久化数据 结束
		
		//删除pdf文件
		data.setDownloadcode(downloadcode);
		data.setMsg(msg);
		data.setCode(code);
		result.setData(data);
		
		creditApiService.insert("", params.getSystem().getVendor_key(), params.getSystem().getVendor_secret(), code, req.getServletPath());
		return result;
	}
	
	/**
	 * pdf转换
	 * @param pdfPath:
	 * @param report_id:
	 * @param req:
	 * @return 
	 */
	@ApiIgnore
	@ApiOperation(value="pdf转换(供内部平台使用)",notes="pdf转换供内部平台使用，且支持同时转换图片")
	@RequestMapping(value = "/convertPdf", method = RequestMethod.POST)
	public CreditConvertPdfRsp convertPdf(@RequestBody CreditConvertPdfReq params) {
		CreditConvertPdfRsp result=new CreditConvertPdfRsp();
		Integer code=1;
		String msg="成功";
		String fileContent=params.getFileContent();
		Integer report_id=params.getReport_id();//report_id report表ID，t_credit_report
		String txtPath=params.getTxtPath();//文件存储路径，oss转换完后需要转存pdf文档
		String pdfPath=crdPdfConvertProperties.getLocalPdfPath();
		String pdfName=UUIDUtil.getUUIDUnline();
		if(TextUtils.isEmpty(fileContent)||TextUtils.isEmpty(txtPath)||report_id==null) {
			code=-1;
			msg="缺少必要参数";
		}
		boolean pdfFlag=code!=null&&code.equals(1)?FileUtil.checkPdfBase64(fileContent):false;//判断是否为pdf文件
		
		if(code!=null&&code.equals(1)&&!pdfFlag) {
			code=-1;
			msg="不是pdf文件，请检查参数";	
			log.info("convertPdf fileContent:"+fileContent);
		}
		//第一步，本地存储pdf
		if(code!=null&&code.equals(1)) {
			Base64Util.bs64stringToFile(fileContent, pdfPath + pdfName + ".pdf");//转换成文件存储在pafPath位置，文件名称为pdfName.pdf，然后上传到oss
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//存储目录
			String date = sdf.format(new Date());
			sdf.applyPattern("HH");
			String monthDay = sdf.format(new Date());
			
			String destPath = crdPdfConvertProperties.getOss_key()+ date + "/" + monthDay + "/";//上传到oss的路径
			
			//第二步，上传本地存储pdf
			uploadPDF(pdfPath + pdfName + ".pdf", destPath+pdfName+".pdf");// 第一步上传pdf到oss
			
			
			//第三步，通知ocr进行转换excel
			Integer status=execuateOcr("excel4hide", destPath+pdfName + ".pdf");
			
			code=status;
			msg=code==null||!code.equals(1)?"转换失败，请确认pdf为符合要求的文件":msg;
			//数据存储转换信息
			
			//数据存储 存储report_id txtPath uuid 文件名称
			this.creditCvthpdfService.insertCvthpdf(report_id, txtPath, pdfName);
			
			PdfToImageUtil.pdfConvertImage(Base64Util.bs64stringToBytes(fileContent), txtPath);//将pdf转换为图片备用
			PDFTextReader.noStatusConvert(pdfPath + pdfName + ".pdf", txtPath + ".xls");
			
			//call 时获取到 通过uuid获取到report_id txtPath 修改标记
			
			//OssUtil.updloadPDF(filePath, endpoint, keyId, secret, bucketName, key);
		}
		CreditConvertPdfRspData data=new CreditConvertPdfRspData();
		data.setCode(code);
		data.setMsg(msg);
		result.setData(data);
		return result;
	}
	
	private String saveDate(CreditApplyCreditReportReq params,Map<String,Object> ossFileNameList){
		String downloadcode=UUIDUtil.getUUIDUnline();
		String pwd = RandomUtil.randomString(8);// 密码
		String key = RandomUtil.randomString(8);// 秘钥
		//String aespwd = AesUtil.encrypt(pwd, key);
		String vendor_key=params.getSystem().getVendor_key();
		String vendor_secret=params.getSystem().getVendor_secret();
		String identify=params.getData().getIdentify();
		String convertType=params.getData().getConvertType();
		Integer user_id = this.creditAuothService.queryAuoth(vendor_key, vendor_secret);// 是否授权厂商
		
		List<String> pdfFileNames=(List<String>)ossFileNameList.get("pdfs");
		for (String string : pdfFileNames) {
			CreditCsvConvert creditCsvConvert=new CreditCsvConvert();
			creditCsvConvert.setApplytype(1);
			creditCsvConvert.setAuoth_id(user_id);
			creditCsvConvert.setConvertnum(1);
			creditCsvConvert.setConverttype(convertType);
			creditCsvConvert.setPdfname(string);
			creditCsvConvert.setCredit_queryid("");
			creditCsvConvert.setCreated_at(new Date());
			creditCsvConvert.setUpdated_at(new Date());
			creditCsvConvert.setDownloadcode(downloadcode);
			creditCsvConvert.setIdentify("");
			creditCsvConvert.setStatus(0);
			creditCsvConvert.setVendor_key(vendor_key);
			Integer csvconvertid=this.creditCsvConvertService.insert(creditCsvConvert);
			
			CreditCsv creditCsv=new CreditCsv();
			creditCsv.setCreated_at(new Date());
			creditCsv.setCsvconvertid(csvconvertid);
			creditCsv.setDeskey(key);
			creditCsv.setDespwd(pwd);
			creditCsv.setDownloadcode(downloadcode);
			creditCsv.setFilename(string);
			creditCsv.setFfilename("");
			creditCsv.setIdentify("");
			creditCsv.setStatus(0);
			creditCsv.setUpdated_at(new Date());
			this.creditCsvService.insert(creditCsv);
		}
		Map<String,String> pdfMap=(Map<String,String>)ossFileNameList.get("pdf");
		if(pdfMap!=null&&pdfMap.get("credit_queryid")!=null) {
			CreditCsvConvert creditCsvConvert=new CreditCsvConvert();
			creditCsvConvert.setApplytype(1);
			creditCsvConvert.setAuoth_id(user_id);
			creditCsvConvert.setConvertnum(1);
			creditCsvConvert.setConverttype(convertType);
			creditCsvConvert.setPdfname("");
			creditCsvConvert.setCredit_queryid(pdfMap.get("credit_queryid"));
			creditCsvConvert.setCreated_at(new Date());
			creditCsvConvert.setUpdated_at(new Date());
			creditCsvConvert.setDownloadcode(downloadcode);
			creditCsvConvert.setIdentify(identify);
			creditCsvConvert.setStatus(0);
			creditCsvConvert.setVendor_key(vendor_key);
			
			Integer csvconvertid=this.creditCsvConvertService.insert(creditCsvConvert);
			
			CreditCsv creditCsv=new CreditCsv();
			creditCsv.setCreated_at(new Date());
			creditCsv.setCsvconvertid(csvconvertid);
			creditCsv.setDeskey(key);
			creditCsv.setDespwd(pwd);
			creditCsv.setDownloadcode(downloadcode);
			creditCsv.setFilename(pdfMap.get("credit_queryid"));
			creditCsv.setFfilename("");
			creditCsv.setIdentify(identify);
			creditCsv.setStatus(0);
			creditCsv.setUpdated_at(new Date());
			this.creditCsvService.insert(creditCsv);
		}
		return downloadcode;
	}
	
	/**
	 * 上传oss
	 * @param sysJsonObject 
	 * @param dataJsonObject
	 * @param date String 日期格式yyyy-MM-dd
	 * @param monthDay String 一月的第多少天
	 * @return
	 */
	private Map<String,Object> uploadOSS(CreditApplyCreditReportReq param,String date,String monthDay){
		String identify = param.getData().getIdentify();
		//Integer convertType = dataJsonObject.getInteger("convertType");
		List<String> pafsJsonArray = param.getData().getPdfs();
		String pdfPath=crdPdfConvertProperties.getLocalPdfPath();//env.getProperty("credit.pdf.filepath");//本地指定pdf存储路径]
		String destPath = crdPdfConvertProperties.getOss_key()+ date + "/" + monthDay + "/";//上传到oss的路径
		
		List<String> pdfFileNames=new ArrayList<String>();
		//String downloadcode=UUIDUtil.getUUIDUnline();//下载码
		Map<String,Object> resultMap=new HashMap<String, Object>();
		if(pafsJsonArray!=null&&pafsJsonArray.size()>0) {
			for (int i = 0; i < pafsJsonArray.size(); i++) {
				String pdfStr=pafsJsonArray.get(i);
				String pdfName=UUIDUtil.getUUIDUnline();
				pdfFileNames.add(pdfName);
				Base64Util.bs64stringToFile(pdfStr, pdfPath + pdfName + ".pdf");//转换成文件存储在pafPath位置，文件名称为pdfName.pdf，然后上传到oss
				uploadPDF(pdfPath + pdfName + ".pdf", destPath+pdfName+".pdf");// 第一步上传pdf到oss
			}
		}
		if(identify!=null&&!identify.trim().equals("")){
			String pdfName = this.creditLogService.selectPDFByIdentity(identify);//得到pdf文件名称
			
			//复制文件命名为UUID
			String pdfNameTemp=UUIDUtil.getUUIDUnline();
			FileUtil.copyFile(pdfPath + pdfName + ".pdf", pdfPath + pdfNameTemp + ".pdf");
			
			
			uploadPDF(pdfPath + pdfNameTemp + ".pdf", destPath+pdfNameTemp+".pdf");// 第一步上传pdf到oss
			Map<String,String> temp=new HashMap<>();
			temp.put("credit_queryid", pdfNameTemp);
			resultMap.put("pdf", temp);
			//pdfFileNames.add(pdfName);
		}
		resultMap.put("pdfs", pdfFileNames);
		return resultMap;
	}

	private Integer actionOcr(CreditApplyCreditReportReq param,Map<String,Object> pdfFileMap,String date,String monthDay){
		String convertType = param.getData().getConvertType();//转换类型，如果是doc，调用word如果是excel，调用Excel，如果是json调json
		
		String destPath="/"+crdPdfConvertProperties.getOss_key() + date + "/" + monthDay + "/";
		
		String pdfPath=crdPdfConvertProperties.getLocalPdfPath();//env.getProperty("credit.pdf.filepath");//本地指定pdf存储路径]
		List<String> pdfFileNames=(List<String>)pdfFileMap.get("pdfs");
		Integer status=1;
		for (String pdfFileName : pdfFileNames) {
			FileUtil.deleteFile(pdfPath + pdfFileName + ".pdf");
			status=execuateOcr(convertType, destPath+pdfFileName+".pdf");
		}
		Map<String,String> pdfMap=(Map<String,String>)pdfFileMap.get("pdf");
		if(pdfMap!=null&&pdfMap.get("credit_queryid")!=null) {
			FileUtil.deleteFile(pdfPath + (String)pdfMap.get("credit_queryid") + ".pdf");
			status=execuateOcr(convertType, destPath+(String)pdfMap.get("credit_queryid")+".pdf");
		}
		return status;
	}
	
	/**
	 * 通知pdf转换csv 0：失败，1：成功 2：识别中
	 * 
	 * @param destPath,转换目标文件
	 * @return
	 */
	private Integer execuateOcr(String convertType,String fileName) {
		String resultStr = "";
		try {
			String orcUrl="";
			if(convertType.equals("excel")) {
				orcUrl=crdPdfConvertProperties.getExcelService();
			}else if(convertType.equals("word")) {
				orcUrl=crdPdfConvertProperties.getWordService();
			}else if(convertType.equals("json")) {
				orcUrl=crdPdfConvertProperties.getJsonService();
			}else if(convertType.equals("excel4hide")) {
				orcUrl=crdPdfConvertProperties.getExcel4hideService();
			}else{
				orcUrl=crdPdfConvertProperties.getDefaultService();
			}
			log.info("url:" + orcUrl + " /ndestPath:" + fileName+ " /convertType:" + convertType);
			
			JSONObject fileNameJson=new JSONObject();
			fileNameJson.put("pdf", fileName);
			fileNameJson.put("url", crdPdfConvertProperties.getCallBackApi());
			log.info("fileNameJson:"+fileNameJson.toJSONString());
			resultStr = HttpUtil.execuateHttpBasicAuth(orcUrl, "post",crdPdfConvertProperties.getConvertUsername(), crdPdfConvertProperties.getConvertPwd(), null, fileNameJson.toJSONString());
			log.info("info:" + resultStr);
		} catch (Exception e) {
			log.error("error:", e);
		}
		Integer status = 0;
		if (resultStr != null && !resultStr.equals("")) {
			status = JSONObject.parseObject(resultStr).getInteger("status");
		}
		return status;
	}
	
	/**
	 * 征信报告下载 完成
	 * 
	 * @return
	 */
	@ApiOperation(value="获取转换结果",notes="发起pdf报告转换申请成功后,可以通过该接口获取转换结果")
	@RequestMapping(value = "/getCreditReport", method = RequestMethod.POST)
	public CreditGetCreditReportRsp getCreditReport(@RequestBody CreditGetCreditReportReq params,HttpServletRequest req) {
		CreditGetCreditReportRsp result=new CreditGetCreditReportRsp();
		CreditGetCreditReportRspData data=new CreditGetCreditReportRspData();
		Integer applyTotal=0;
		Integer successTotal=0;
		Integer failTotal=0;
		Integer nullTotal=0;
		
		Integer code=1;
		String msg="";
		String deskey="";
		String despwd="";
		String credits="";
		
		data.setApplytotal(applyTotal);
		data.setConverting(nullTotal);
		data.setCredits(credits);
		data.setDeskey(deskey);
		data.setDespwd(despwd);
		data.setFailtotal(failTotal);
		data.setSuccesstotal(successTotal);
		if(params.getSystem()==null||
				params.getData()==null||
				TextUtils.isEmpty(params.getSystem().getVendor_key())||
				TextUtils.isEmpty(params.getSystem().getVendor_secret())||
				TextUtils.isEmpty(params.getData().getDownloadcode())) {
			msg="缺少必須參數";
			code=-1;
		}
		CreditApplyCreditReportRspData creditReportDataRspInfo=code.equals(1)?roleCheck(params.getSystem().getVendor_key(),params.getSystem().getVendor_secret(),null):new CreditApplyCreditReportRspData();//校验是否授权厂商
		if(code.equals(1)) {
			code=creditReportDataRspInfo.getCode();
			msg=creditReportDataRspInfo.getMsg();
		}
		String downloadCod=params.getData().getDownloadcode();
		CreditCsv creditCsv=code.equals(1)?this.creditCsvService.checkDlownloadFlag(downloadCod):null;//校验是否转换完
		List<Map<String,Object>> creditCsvSizeInfo=code.equals(1)?this.creditCsvService.getDownloadSizeInfoByDownloadcode(downloadCod):new ArrayList<Map<String,Object>>();
		for (Map<String, Object> map : creditCsvSizeInfo) {
			Integer status=(Integer)map.get("status");
			Integer statuscount=Integer.valueOf(((Long)map.get("statuscount")).toString());
			if(status.equals(-1)) {
				failTotal+=statuscount;
			}else if(status.equals(0)) {
				nullTotal+=statuscount;
			}else if(status.equals(1)) {
				successTotal+=statuscount;
			}
			applyTotal+=statuscount;
		}
		CreditCsv creditCsvInfo=code.equals(1)?this.creditCsvService.getCreditCsvByDownloadCode(downloadCod):null;
		deskey=creditCsvInfo==null||creditCsvInfo.getDeskey()==null?"":creditCsvInfo.getDeskey();
		despwd=creditCsvInfo==null||creditCsvInfo.getDeskey()==null?"":AesUtil.encrypt(creditCsvInfo.getDespwd(), creditCsvInfo.getDeskey());
		if(code.equals(1)&&creditCsvInfo!=null&&creditCsv==null&&applyTotal.equals(successTotal)) {//全部转换成功的
			code=1;
			msg="全部转换成功";
			credits=crdPdfConvertProperties.getResultDownUrl()+downloadCod;
		}else if(code.equals(1)&&creditCsvInfo!=null&&creditCsv==null&&successTotal>0&&failTotal>0){//部分转换成功的
			code=1;
			msg="部分转换成功,失败部分可能因为文件格式或内容排版不符合要求";
			credits=crdPdfConvertProperties.getResultDownUrl()+downloadCod;
		}else if(code.equals(1)&&creditCsvInfo!=null&&creditCsv==null&&applyTotal.equals(failTotal)) {//全部转换失败的
			code=1;
			msg="全部转换失败,可能因为文件格式或内容排版不符合要求";
		}else if (code.equals(1)&&creditCsvInfo!=null&&creditCsv!=null) {
			code=0;
			msg="转换中,请稍后再试";
			deskey="";
			despwd="";
		}else if(code.equals(1)&&creditCsvInfo==null){
			code=-1;
			msg="请确认是否做了转换申请";
		}
		data.setApplytotal(applyTotal);
		data.setCode(code);
		data.setConverting(nullTotal);
		data.setCredits(credits);
		data.setDeskey(deskey);
		data.setDespwd(despwd);
		data.setFailtotal(failTotal);
		data.setMsg(msg);
		data.setSuccesstotal(successTotal);
		
		result.setData(data);
		creditApiService.insert("", params.getSystem().getVendor_key(), params.getSystem().getVendor_secret(), code, req.getServletPath());
		return result;
	}

	/**
	 * 回调接口
	 * 
	 * @return
	 */
	@ApiIgnore
	@ApiImplicitParams({
        @ApiImplicitParam(name = "pdf", value = "原文件ID", required = true,paramType="query" ),
        @ApiImplicitParam(name = "status", value = "成功状态，1成功，0失败", required = true,paramType="query"),
        @ApiImplicitParam(name = "message", value = "提示信息", required = true,paramType="query"),
        @ApiImplicitParam(name = "type", value = "回调转换类型", required = true,paramType="query")
	})
	@ApiOperation(value="pdf转换服务回调api",notes="pdf转换服务回调api,参数?pdf=下载码&status=1&message=jdsj&type")
	@RequestMapping(value = "/callBack", method = RequestMethod.GET)
	public String callBack(@RequestParam("pdf") String pdf,
			@RequestParam("status") String status,
			@RequestParam("message") String message,
			@RequestParam("type") String type,
			HttpServletRequest req) {
		//String type = req.getParameter("type");
		JSONObject result=new JSONObject();
		if(type.equals("excel4hide")) {
			result=callBackExcel4hide(pdf,status,message,type);
		}else {
			result=callBackOther(pdf,status,message,type);
		}
		//String pdfFileName = req.getParameter("pdf");//pdf:为原pdf文件名称
		//String status = req.getParameter("status");//是否成功标志
		//String message = req.getParameter("message");///tmp/oss2/pdf/excel/xxxxx.xls
		if(status != null && status.equals("1")) {
			log.info("info callBack pdfConvert successful:" + pdf);
			log.info("info callBack pdfConvert successful:" + message);
		}else {
			log.info("info callBack pdfConvert fail:" + pdf);
			log.info("info callBack pdfConvert fail:" + message);
			log.info("info callBack pdfConvert fail:" + status);
			log.info("info callBack pdfConvert fail:" + type);
		}
		return result.toJSONString();
	}
	
	private JSONObject callBackExcel4hide(String pdf,String status,String message,String type) {
		JSONObject resultJson = new JSONObject();
		JSONObject dataJson = new JSONObject();
		//String pdfFileName = req.getParameter("pdf");//pdf:为原pdf文件名称
		//String status = req.getParameter("status");//是否成功标志
		//String message = req.getParameter("message");///tmp/oss2/pdf/excel/xxxxx.xls
		String pdfName=pdf.substring(0, pdf.lastIndexOf(".pdf"));//uuid
		if(status != null && status.equals("1")) {//修改report表  从oss拉取文件到本地
			CreditCvthpdf creditCvthpdf=this.creditCvthpdfService.getCvthpdfByPdfName(pdfName);
			this.creditCvthpdfService.updateReportFlag(creditCvthpdf.getReport_id());
			String ossPath=message.substring(0, 1).equals("/")?message.substring(1,message.length()):message;
			downloadCsv(ossPath, creditCvthpdf.getTxtPath()+".xls");
		}
		dataJson.put("code", 1);
		dataJson.put("msg", "成功");
		resultJson.put("data", dataJson);
		return resultJson;
	}
	
	private JSONObject callBackOther(String pdf,String status,String message,String type) {
		
//		String pdfFileName = req.getParameter("pdf");//pdf:为原pdf文件名称
//		String status = req.getParameter("status");//是否成功标志
//		String message = req.getParameter("message");///tmp/oss2/pdf/excel/xxxxx.xls
//		String type = req.getParameter("type");///excel(图片版海矩Excel)，excel2（文字版表格Excel），excel4haiju（文字版海矩Excel），word（文字版表格Word），json（文字版JSON），excel4hide（文字版脱敏excel）
		JSONObject resultJson = new JSONObject();
		JSONObject dataJson = new JSONObject();
		try {
			pdf = pdf.substring(0, pdf.lastIndexOf(".pdf"));//短文件名称,不包含后缀
			
			
			String xlsFileName=message.substring(message.lastIndexOf("/")+1,message.length());//oss端文件名称包含后缀
			
			String ossPath=message.substring(1,message.length());//oss段文件路径,用于下载到本地
			//得到 csv，csconvert，设置为status为成功状态
			if(status != null && status.equals("1")) {
				this.creditCsvConvertService.update(pdf, Integer.valueOf(status));
				this.creditCsvService.update(pdf,xlsFileName, Integer.valueOf(status));
				//将文件下载到本地
				downloadCsv(ossPath, crdPdfConvertProperties.getLocalResultPath() + xlsFileName);
				//判断是压缩成zip
				CreditCsv creditCsv=this.creditCsvService.checkZipFlag(pdf);
				if(creditCsv==null) {//表示所有文件已经转换完毕
					List<CreditCsv> list=this.creditCsvService.getZipFile(pdf);
					String downloadcode="";
					String deskey="";
					String despwd="";
					ArrayList<String> filesToAddStr=new ArrayList<String>();
					for (CreditCsv creditCsv2 : list) {
						downloadcode=downloadcode==null||downloadcode.equals("")?creditCsv2.getDownloadcode():downloadcode;
						despwd=despwd==null||despwd.equals("")?creditCsv2.getDespwd():despwd;
						String filePath=crdPdfConvertProperties.getLocalResultPath()+creditCsv2.getFfilename();
						if(!filesToAddStr.contains(filePath)) {
							filesToAddStr.add(filePath);
						}
					}
					if(filesToAddStr!=null&&filesToAddStr.size()>0) {
						ZipUtil.AddFilePathsWithPwd(crdPdfConvertProperties.getLocalResultPath() + downloadcode + ".zip", filesToAddStr, despwd);
					}
				}
				dataJson.put("code", 1);
				dataJson.put("msg", "成功");
				log.info("info:" + "成功");
			}else {
				this.creditCsvConvertService.update(pdf, Integer.valueOf(-1));
				this.creditCsvService.update(pdf,"", Integer.valueOf(-1));
				dataJson.put("code", -1);
				dataJson.put("msg", "转换失败");
				log.info("info:" + "转换失败-pdfFileName:"+pdf+"--message:"+message);
			}
		} catch (Exception e) {
			dataJson.put("code", -1);
			dataJson.put("msg", "系统错误!");
			log.error("error:", e);
		}
		resultJson.put("data", dataJson);
		return resultJson;
	}

	/**
	 * 文件下载
	 * 
	 * @param res
	 * @throws IOException
	 */
	@ApiOperation(value="下载转换结果文件",notes="下载转换结果文件,参数?credit_queryid=下载码")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "credit_queryid", value = "下载标识", required = true,paramType="query" ),
	})
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public void downloadFile(@RequestParam("credit_queryid") String credit_queryid,HttpServletRequest req, HttpServletResponse res) throws Exception {
		//String credit_queryid = req.getParameter("credit_queryid");
		
		JSONObject resultJson = new JSONObject();
		JSONObject dataJson = new JSONObject();
		CreditCsv creditCsv=this.creditCsvService.checkDlownloadFlag(credit_queryid);//校验是否转换完
		List<Map<String,Object>> creditCsvSizeInfo=this.creditCsvService.getDownloadSizeInfoByDownloadcode(credit_queryid);
		Integer applyTotal=0;
		Integer successTotal=0;
		Integer failTotal=0;
		Integer nullTotal=0;
		for (Map<String, Object> map : creditCsvSizeInfo) {
			Integer status=(Integer)map.get("status");
			Integer statuscount=Integer.valueOf(((Long)map.get("statuscount")).toString());
			//Integer.valueOf(statuscountd.);
			if(status.equals(-1)) {
				failTotal+=statuscount;
			}else if(status.equals(0)) {
				nullTotal+=statuscount;
			}else if(status.equals(1)) {
				successTotal+=statuscount;
			}
			applyTotal+=statuscount;
		}
		
		if(creditCsv==null&&successTotal>0) {//可以下载
			res.setHeader("content-type", "application/octet-stream");
			res.setContentType("application/octet-stream");
			res.setHeader("Content-Disposition", "attachment;filename=" + credit_queryid + ".zip");
			try {
				File file = new File(crdPdfConvertProperties.getLocalResultPath() + credit_queryid + ".zip");
				FileInputStream fin = new FileInputStream(file);
				res.setContentLengthLong(file.length());
				OutputStream outputStream = res.getOutputStream();
				byte[] buff = new byte[1024];
				int i = fin.read(buff);
				while (i != -1) {
					outputStream.write(buff, 0, buff.length);
					outputStream.flush();
					i = fin.read(buff);
				}
				fin.close();
			} catch (Exception e) {
				log.error("",e);
				res.setCharacterEncoding("UTF-8");
				res.setHeader("Content-type", "text/json;charset=UTF-8");
				dataJson.put("code", -1);
				dataJson.put("msg", "没有找到下载文件,可能因为转换失败,或者还在转换中请稍后再试");
				resultJson.put("data", dataJson);
				res.getWriter().println(resultJson);
				return;
			}
		}else{//不能下载
			res.setCharacterEncoding("UTF-8");
			res.setHeader("Content-type", "text/json;charset=UTF-8");
			dataJson.put("code", -1);
			dataJson.put("msg", "没有找到下载文件,可能因为转换失败,或者还在转换中请稍后再试");
			resultJson.put("data", dataJson);
			res.getWriter().println(resultJson);
			return;
		}
	}
	
	/**
	 * 征信报告下载(pdf)
	 * @param params
	 * @return
	 */
	@ApiOperation(value="征信报告下载",notes="征信报告下载(原报告)")
	@ApiIgnore
	@RequestMapping(value = "/creditDownload", method = RequestMethod.POST)
	public CreditCrdDldRsp creditDownload(@RequestBody CreditCrdDldReq params,HttpServletRequest req) {
		CreditCrdDldRsp result=new CreditCrdDldRsp();
		Integer code=1;
		String msg="1";
		String contentBase64="";
		if(params.getSystem()==null||
				params.getData()==null||
				TextUtils.isEmpty(params.getSystem().getVendor_key())||
				TextUtils.isEmpty(params.getSystem().getVendor_secret())||
				TextUtils.isEmpty(params.getData().getIdentify())) {
			code=-1;
			msg="缺少必须参数";
		}
		CreditApplyCreditReportRspData dataTemp=code.equals(1)?roleCheck(params.getSystem().getVendor_key(),params.getSystem().getVendor_secret(),params.getData().getIdentify()):null;//校验是否厂商,或者是否身份证号码是他的所属
		if(code.equals(1)&&dataTemp!=null) {
			code=dataTemp.getCode();
			msg=dataTemp.getMsg();
		}
		String pdfName = code.equals(1)?this.creditLogService.selectPDFByIdentity(params.getData().getIdentify()):"";//得到pdf文件名称
		if(code.equals(1)&&TextUtils.isEmpty(pdfName)) {
			code=-1;
			msg="没有该人员的可用征信报告下载!";
		}
		if(code.equals(1)&&!TextUtils.isEmpty(pdfName)) {
			String pdfPath=crdPdfConvertProperties.getLocalPdfPath()+pdfName+".pdf";//env.getProperty("credit.pdf.filepath");//本地指定pdf存储路径]
			String fileBase64=Base64Util.fileToBase64String(pdfPath);
			contentBase64= fileBase64;
		}
		creditApiService.insert("", params.getSystem().getVendor_key(), params.getSystem().getVendor_secret(), code, req.getServletPath());
		
		CreditCrdDldRspData data=new CreditCrdDldRspData();
		data.setCode(code);
		data.setMsg(msg);
		data.setContentBase64(contentBase64);
		result.setData(data);
		return result;
	}
	
	/**
	 * 权限教研，厂商是否具有权限，identity是否在该厂商下
	 */
	private CreditApplyCreditReportRspData roleCheck(String vendor_key,String vendor_secret,String identify) {
		Integer user_id = this.creditAuothService.queryAuoth(vendor_key, vendor_secret);// 是否授权厂商
		CreditApplyCreditReportRspData result=new CreditApplyCreditReportRspData();
		Integer code = 1;
		String msg = "成功!";
		if (user_id == null) {
			code = -1;
			msg = "拒绝非授权厂商调用";
		}
		if (code.equals(1)&&identify != null && !identify.equals("")) {
			List<String> tempList = this.creditLogService.checkIdentifyByCs(vendor_key,vendor_secret, identify);
			if (tempList == null || tempList.size() <= 0) {
				code = -1;
				msg = "该厂商下没有该身份的征信报告可查";
			}
		}
		result.setCode(code);
		result.setMsg(msg);
		result.setDownloadcode("");
		return result;
	}

	/**
	 * 上传pdf到oss
	 * 
	 * @param pdfPath
	 */
	private void uploadPDF(String pdfPath, String destPath) {
		OssUtil.updloadPDF(pdfPath, crdPdfConvertProperties.getOss_endpoint(), crdPdfConvertProperties.getOss_keyid(),
				crdPdfConvertProperties.getOss_secrect(), crdPdfConvertProperties.getOss_bucket(), destPath);
	}

	/**
	 * 上传pdf到oss
	 * 
	 * @param pdfPath
	 */
	private void downloadCsv(String ossPath, String destPath) {
		log.info("info callBack downloadCsv destPath:" + destPath);
		log.info("info callBack downloadCsv ossPath:" + ossPath);
		OssUtil.downloadPDF(crdPdfConvertProperties.getOss_endpoint(), crdPdfConvertProperties.getOss_keyid(),
				crdPdfConvertProperties.getOss_secrect(), crdPdfConvertProperties.getOss_bucket(), ossPath, destPath);
	}
}
